package com.example.pceb.controller;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.example.pceb.DTO.ResumeDto;
import com.example.pceb.common.R;
import com.example.pceb.entity.Recruit;
import com.example.pceb.entity.Resume;
import com.example.pceb.result.Result;
import com.example.pceb.service.RecruitService;
import com.example.pceb.service.ResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.*;

//关于简历功能
@RestController
@RequestMapping("/resume")
//@CrossOrigin(origins = "*")
public class ResumeController {
    @Autowired
    private ResumeService resumeService;
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    @Autowired
    private RecruitService recruitService;
    // 查询简历
    @GetMapping("info")
    public Result<Resume> getResume(@RequestParam String username) {
        Resume resume = resumeService.getByUsername(username);
        return Result.success(resume);
    }

    // 保存或更新简历
    @PostMapping("save")
    public Result<?> saveResume(@RequestBody Resume resume) {
        resumeService.saveOrUpdateResume(resume);
        return Result.success();
    }

//    @PostMapping("import")
//    public Resume importPdf(@RequestParam("file") MultipartFile file) throws Exception {
//        PDDocument document = PDDocument.load(file.getInputStream());
//        PDFTextStripper stripper = new PDFTextStripper();
//        String content = stripper.getText(document);
//        document.close();
//        Resume resume = parseResumeFromText(content);
//        return resume;
//    }

    //上传头像
    // 上传头像并返回签名URL
    @PostMapping("/uploadAvatar")
    public Map<String, Object> uploadAvatar(@RequestParam("file") MultipartFile file,
                                            @RequestParam("username") String username) {
        Map<String, Object> result = new HashMap<>();
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 构建唯一文件名
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
            String objectName = "avatar/" + username + "_" + UUID.randomUUID() + ext;

            // 上传到OSS
            ossClient.putObject(bucketName, objectName, file.getInputStream());

            // 生成签名URL（1小时有效）
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
            GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
            req.setExpiration(expiration);
            URL signUrl = ossClient.generatePresignedUrl(req);

            result.put("url", signUrl.toString());
            result.put("code", 200);
            result.put("msg", "上传成功");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "上传失败：" + e.getMessage());
        } finally {
            if (ossClient != null) ossClient.shutdown();
        }
        return result;
    }

    @PostMapping("/recommend")
    public R recommend(@RequestBody ResumeDto resume) {
        List<Recruit> jobs = recruitService.recommendJobs(resume);
        return R.ok(jobs);
    }
}
